﻿using AutoMapper;
using B.X.Rabbit.Domain.RBAC;
using B.X.Rabbit.ErrorCode;
using B.X.Rabbit.Infrastructure;
using B.X.Rabbit.Read.Api.Application.Command.Login;
using B.X.Rabbit.Read.Api.DTO;
using MD5Hash;
using MediatR;
using System.Security.Cryptography;
using System.Text;

namespace B.X.Rabbit.Read.Api.Application.CommandHandler.Login
{
    /// <summary>
    /// 登录
    /// </summary>
    public class LoginQueryCommandHandler : IRequestHandler<LoginQueryCommand, ApiResult<UserDto>>
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        IBaseReponsitory<User> userRepo;
        /// <summary>
        /// 角色仓储
        /// </summary>
        IBaseReponsitory<Role> roleRepo;
        /// <summary>
        /// 用户角色仓储
        /// </summary>
        IBaseReponsitory<UserRole> userroleRepo;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="userRepo">用户仓储</param>
        /// <param name="roleRepo">角色仓储</param>
        /// <param name="userroleRepo">用户角色仓储</param>
        public LoginQueryCommandHandler(IBaseReponsitory<User> userRepo, IBaseReponsitory<Role> roleRepo, IBaseReponsitory<UserRole> userroleRepo)
        {
            this.userRepo = userRepo;
            this.roleRepo = roleRepo;
            this.userroleRepo = userroleRepo;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">请求</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<UserDto>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<UserDto> result = new ApiResult<UserDto>();
            result.Code = ResultCode.登录成功;
            result.Msg = ResultCode.登录成功.ToString();

            try
            {
                var list = from a in userRepo.GetAll()
                           join b in userroleRepo.GetAll() on a.UserId equals b.UserId
                           join c in roleRepo.GetAll() on b.RoleId equals c.RoleId
                           where a.UserName == request.UserName
                           select new UserDto
                           {
                               UserId = a.UserId,
                               UserName = a.UserName,
                               Password = a.Password,
                               UserNickName = a.UserNickName,
                               RoleId = c.RoleId,
                               RoleName = c.RoleName,

                           };

                if (list == null || list.Count() == 0)
                {
                    throw new Exception("用户名不存在");
                }

                var entity = list.FirstOrDefault();
                request.Password = GetMD5(request.Password);
                if (entity.Password != request.Password)
                {
                    throw new Exception("账号密码不匹配");
                }
                result.Data = entity;
            }
            catch (Exception ex)
            {
                result.Code = ResultCode.登录失败;
                result.Msg = ResultCode.登录失败.ToString() + "" + ex.Message;
            }


            return Task.FromResult(result);
        }
        /// <summary>
        /// 获取md5结果
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns></returns>
        private string GetMD5(string source)
        {
            var md5 = MD5.Create();
            byte[] bytes = Encoding.UTF8.GetBytes(source);
            byte[] hash = md5.ComputeHash(bytes);
            string target = BitConverter.ToString(hash, 0, hash.Length).Replace("-", "");
            return target;
        }
    }
}
